package main

import (
	"os"
	"fmt"
	"io"
)
//文件写入
func WriteFile(path string){
	//打开文件,如果没有文件则新建文件
	file ,err := os.Create(path)
	if err != nil{
		fmt.Println("err=",err)
		return
	}

	//使用完关闭文件流
	defer file.Close()
	var buf string
	for i:=0;i<10;i++{
		buf = fmt.Sprintf("i=%d\n",i)
		n,err := file.WriteString(buf)//返回字符数
		if err != nil{
			fmt.Println("err=",err)
			break
		}
		fmt.Println("n=",n)

	}

}

//文件读取
func ReadFile(path string){
	file ,err := os.Open(path)
	if err != nil{
		fmt.Println("err=",err)
		return
	}

	defer file.Close()
	buf := make([]byte,1024*2)//每次读取2kb大小
	n,err := file.Read(buf)
	if err != nil && err != io.EOF{
		fmt.Println("err=",err)
		return
	}
	fmt.Println("buf=",string(buf[:n]))

}

func main(){
	path := "./demo.txt"
	//WriteFile(path)
	ReadFile(path)
}
